import {
  GET_ABOUT_US,
  GET_OPEN_ID,
  GET_TEACHER_INFO,
  GET_USER_INFO,
  GET_VERSIONS,
  LOGIN_OUT,
  SET_PHONE,
  SET_PLANT,
  SET_TOKEN,
  UPDATE_USER_INFO
} from "../../mutation-types";
import Request from "../../../utils/ajax";

import { Toast } from "../../../utils/modal";
import { NavigateBack, ReLaunch, SwitchTab } from "../../../utils/router";

const {
  open_id,
  login,
  sendMsg,
  userInfo,
  updateUserInfo,
  checkOpenId,
  aboutUs,
  versions,
  teacherInfo,
  exchangeCourse,
  exchangeTrailClass,
  auditions
} = Request.user;

export const setPlanet = ({ commit }) => {
  let plant;
  // #ifdef APP-PLUS
  plant = 'app';
  // #endif

  // #ifdef MP-WEIXIN
  plant = 'wx';
  // #endif
  commit(SET_PLANT, plant);
};

export const getOpenId = async ({ commit }) => {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: "weixin",
      success: async loginRes => {
        try {
          console.log(loginRes);
          let unionid = // 这个openid 其实是 unionid
            (loginRes.authResult && loginRes.authResult.unionid) || "";
          // openid 不存在说明在小程序内
          if (!unionid) {
            let {
              data: { unionid, openid }
            } = await open_id({ code: loginRes.code });
            commit(GET_OPEN_ID, unionid || openid);
            return resolve("wx");
          }
          commit(GET_OPEN_ID, unionid);
          resolve("app");
        } catch (e) {
          reject(e);
        }
      }
    });
  });
};

export const reqCheckOpenId = async ({ commit, state }) => {
  const { open_id } = state;
  try {
    const {
      data: { status }
    } = await checkOpenId({ open_id });
    return status === 1;
  } catch (e) {
    console.log(e);
  }
};

export const reqSendMsg = async ({ commit }, { phone }) => {
  try {
    Toast({
      title: "短信发送中",
      duration: 5000
    });
    await sendMsg({ phone, code: 419768 });
    Toast({
      title: "短信发送成功",
      duration: 1000
    });
    return true;
  } catch (e) {
    return false;
  }
};

export const reqWxLogin = async ({ commit, dispatch }, option) => {
  const payload = {
    type: 2,
    ...option
  };

  try {
    Toast({ title: "登录中。。。", icon: "loading" });
    const { data, message: title } = await login(payload);
    commit(SET_TOKEN, data);
    await dispatch("reqUserInfo", data);
    Toast({
      title,
      duration: 1000,
      success() {
        setTimeout(() => {
          SwitchTab({
            url: "/pages/index/index"
          });
        }, 1000);
      }
    });
  } catch (e) {
    console.log(e);
  }
};

export const reqPhoneLogin = async ({ commit, dispatch }, option) => {
  const payload = {
    type: 1,
    ...option
  };

  try {
    const { phone, code } = option;
    const p = /^1\d{10}$/;
    if (!phone) {
      return Toast({
        title: "请先输入手机号"
      });
    }
    if (!p.test(phone)) {
      return Toast({
        title: "手机号码格式不正确"
      });
    }
    if (!code) {
      return Toast({
        title: "请输入短信验证码"
      });
    }
    Toast({ title: "登录中。。。", icon: "loading" });
    const { data, message: title } = await login(payload);
    commit(SET_TOKEN, data);
    commit(SET_PHONE, phone);
    await dispatch("reqUserInfo", data);
    Toast({
      title,
      duration: 1000,
      success() {
        setTimeout(() => {
          SwitchTab({
            url: "/pages/index/index"
          });
        }, 1000);
      }
    });
  } catch (e) {
    console.log(e);
  }
};

export const loginOut = ({ commit }) => {
  uni.showModal({
    title: "退出",
    content: "确认退出吗？",
    success: res => {
      if (res.confirm) {
        console.log("用户点击确定");
        const phone = uni.getStorageSync("phone");
        uni.clearStorageSync();
        uni.setStorageSync("phone", phone);
        commit(LOGIN_OUT);
        ReLaunch({
          url: "/pages/login/auth/auth"
        });
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    }
  });
};

export const checkToken = async ({ commit, dispatch }) => {
  const token = uni.getStorageSync("token");
  if (token) {
    commit(SET_TOKEN, token);
    await dispatch("reqUserInfo", token);
  } else {
    ReLaunch({ url: "/pages/login/auth/auth" });
  }
};

export const reqUserInfo = async ({ commit, state }) => {
  try {
    const { token } = state;
    const { data } = await userInfo({ token });
    commit(GET_USER_INFO, data);
  } catch (e) {
    console.log(e);
  }
};

export const reqUpdateUserInfo = async (
  { state, commit },
  { type, ...rest }
) => {
  try {
    const { token } = state;
    await updateUserInfo({ token, type, ...rest });
    commit(UPDATE_USER_INFO, rest);
    Toast({ title: "修改成功" });
  } catch (e) {
    console.log(e);
  }
};

export const reqVersions = async ({ commit }) => {
  try {
    const {
      data: { list }
    } = await versions();
    commit(GET_VERSIONS, list);
  } catch (e) {
    console.log(e);
  }
};

export const reqTeachInfo = async ({ commit, state }) => {
  try {
    const { token } = state;
    const { data } = await teacherInfo({ token });
    commit(GET_TEACHER_INFO, data);
  } catch (e) {
    console.log(e);
  }
};

export const reqExchangeCourse = async ({ commit, state }, { code }) => {
  try {
    const { token } = state;
    const res = await exchangeCourse({ token, code });
    if (res.code === 1) {
      Toast({
        title: "兑换成功",
        success() {
          setTimeout(() => NavigateBack(), 1500);
        }
      });
    }
  } catch (e) {
    console.log(e);
  }
};

export const reqAuditions = async ({ state }) => {
  try {
    const { token } = state;
    return await auditions({ token });
  } catch (e) {}
};

export const reqExchangeTrailClass = async ({ state, dispatch }) => {
  try {
    const { token } = state;
    const res = await exchangeTrailClass({ token });
    if (res.code === 1) {
      dispatch("Tools/showModal", {}, { root: true });
    }
  } catch (e) {
    console.log(e);
  }
};

// TODO: 关于我们 退费政策
export const reqAboutUs = async ({ commit }, { name }) => {
  try {
    const { data } = await aboutUs({ name });
    console.log(data);
    commit(GET_ABOUT_US, data);
  } catch (e) {}
};

export const setPhone = async ({ commit }) => {};
